package org.chaiyi.template.core.register.support.bean;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.chaiyi.template.core.common.common.BeanNameManage;
import org.chaiyi.template.core.common.supporter.Supporter;
import org.chaiyi.template.core.framework.support.SupporterCache;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 自动添加SupporterCache的bean定义
 * 使用Spring提供的扫描方式
 * @author Gong.Yang
 */
@Slf4j
@Order(-100)
@Component
public class SupporterCacheRegister implements BeanDefinitionRegistryPostProcessor {


    @Override
    @SneakyThrows
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AssignableTypeFilter(Supporter.class));

        Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents("org.chaiyi.template.contract.supporter");
        for (BeanDefinition beanDefinition : candidateComponents) {
            String beanClassName = beanDefinition.getBeanClassName();
            Class<?> aClass = Class.forName(beanClassName);
            AbstractBeanDefinition repositoryDefinition = BeanDefinitionBuilder.genericBeanDefinition(SupporterCache.class)
                    .addConstructorArgValue(aClass) //剩下的另一个参数会自动注入
                    .getBeanDefinition();

         String beanName = BeanNameManage.getSupportCacheName(aClass);
            registry.registerBeanDefinition(beanName,repositoryDefinition);
        }
        log.info("【Definition】SupporterCache complete!");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
